<?php
/*
   Copyright 2012 BiSe Trojanov

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
 $sad_version='0.4.11';
 list($sad_u1m_sec,$sad_u1s_sec)=explode(' ',microtime());

 //preset $sad_
 $sad_temp_id      =0;                                 // for buttons and {#property
 $sad_hidewtime    =true;                              // hide run  time in the of page; May be set in config.php
 $sad_hidetimestamp=true;                              // hide timestamp in the of page; May be set in config.php
 $sad_etag_cache   =true;                              // E-tag/Last-modified; May be set in config.php

 $_SERVER['REQUEST_URI']=preg_replace('|/+|','/',$_SERVER['REQUEST_URI']);
 if (!isset($sad_inadmin)){$sad_inadmin=false;}        // true if index.php included from administration panel
 if (!isset($sad_inconly)){$sad_inconly=false;}        // true if index.php included from some non-AscetCMS place as library with functions
 if (!$sad_inadmin){
  $sad_root   =preg_replace('|/[^/]+$|','',$_SERVER['SCRIPT_FILENAME']);// document root of cms e.g. /var/www/site
  $sad_baseurl=preg_replace('|/[^/]+$|','',$_SERVER['SCRIPT_NAME']);    // URL root of cms e.g. /cms
 }else{
  $sad_root   =preg_replace('|(.*)/i/.*$|','\1',$_SERVER['SCRIPT_FILENAME']);
  $sad_baseurl=preg_replace('|(.*)/i/.*$|','\1',$_SERVER['SCRIPT_NAME']);
 }

 require_once($sad_root.'/config.php');// Connect to mysql

 if (strpos(' '.$_SERVER['SCRIPT_FILENAME'],$_SERVER['DOCUMENT_ROOT'].'/')==1){
  $sad_rurl=preg_replace('|\\?.*$|','',$_SERVER['REQUEST_URI']); // request URL e.g. /cms/script.php
  $sad_purl=substr($_SERVER['REQUEST_URI'],strlen($sad_baseurl));// param URL   e.g. /script.php?param
  $sad_url =substr($sad_rurl,strlen($sad_baseurl));              // TRUE URL without params e.g. /script.php
                                                                 // Try to use $sad_url instead of the others
 }else{
  //AliasMatch in .htaccess
  header('http/1.0 501');
  exit;
 }
 
 // content-type in headers
 $sad_contype='';
 preg_match('|\\.([a-z0-9]+)$|',$sad_url,$sad_t1);
 switch(strtolower($sad_t1[1])){
  case 'css': $sad_contype='text/css; charset=utf-8';break;
  case 'js':  $sad_contype='application/javascript; charset=utf-8';break;
  case 'txt': $sad_contype='text/plain; charset=utf-8';break;
  case 'jpg':case 'jpeg': $sad_contype='image/jpeg';break;
  case 'png': $sad_contype='image/png';break;
  case 'gif': $sad_contype='image/gif';break;
  case 'ico': $sad_contype='image/vnd.microsoft.icon';break;
  default: $sad_contype='text/html; charset=utf-8';
 }
 unset($t1); 
 
 $sad_protocol='http';
 if (isset($_SERVER['HTTPS'])){if ($_SERVER['HTTPS']=='on'){$sad_protocol='https';}}

 //functions "safe"
 function sad_safe_domain($domain){
  $s=strtolower($domain);$a=explode(':',$s,2);$s=$a[0];
  if (preg_match_all('|\\.|',$s,$sad_tmp)>1){
   $s=preg_replace('|^www\\.(.+?)$|','$1',$s);
  }
  return $s;
 }
 $sad_domain   =sad_safe_domain($_SERVER['HTTP_HOST']);
 
 function sad_safe_html($text){
  return htmlspecialchars($text);
 }

 function sad_safe_mysql($text){
  return str_replace('`','\\`',mysql_escape_string($text));
 }

 function sad_safe_reg($text){
  $ar='.-\\/[]{}?+';
  $s=''; for ($i=0;$i<strlen($text);$i++){
   if (strpos(' '.$ar,$text[$i])>0){
    $s.='\\'.$text[$i];
   }else{
    $s.=$text[$i];
   }
  }
  return $s;
 }

 function sad_safe_path($path){
  $a=explode('/',$path);$s='';
  foreach ($a as $e){
   if ($e=='' or $e=='.' or $e=='..'){continue;}
   $s.='/'.$e;
  }
  return substr($s,1);
 }

 function sad_safe_xml($text,$u=true){
  $b=str_replace(']]>',']]]]><![CDATA[>',$text);
  if ($u){$b='<![CDATA['.$b.']]>';}
  return $b;
 }

 function sad_safe_xmlc($text,$u=true){
  while (preg_match('_\\-\\-_',$text)){$text=preg_replace('_\\-\\-_','- -',$text);}
  if ($u){$text='<!-- '.$text.' -->';}
  return $text;
 }

 //administration cookie
 session_start();
 setcookie(ini_get('session.name'),session_id(),time()+30*24*3600);
 if (isset($_SESSION['sad_rights'])){
  if ($_SESSION['sad_time']+24*3600*7<time()){
   unset($_SESSION['sad_password']);
   unset($_SESSION['sad_rights']);
   unset($_SESSION['sad_time']);
  }else{
   $sad_q_c=mysql_fetch_assoc(mysql_query('select `password` from `'.$sad_prefix.
          '_users` where `login` like "'.sad_safe_mysql($_SESSION['sad_login']).'"'));
   if ($sad_q_c['password']!==$_SESSION['sad_password']){
    mysql_query('insert into `'.$sad_prefix.'_history` (`title`,`text`,'.
                '`time`) values ("User forced logged off","User '.
                sad_safe_html($_SESSION['sad_login']).' logged off cos '.
                'incorrect password at '.gmdate('Y-m-d-H-i-sO').
                '", '.time().')');
    unset($_SESSION['sad_password']);
    unset($_SESSION['sad_rights']);
    unset($_SESSION['sad_time']);
   }
   unset($sad_q_c);
  }
 }


 //Create tables
 $te=array('data'=>false,'_visits'=>false,'_users'=>false,'_history'=>false,'_options'=>false);
 $te_i =implode('|',array_keys($te));
 $sad_q=mysql_query('show tables');
 while ($sad_q_c=mysql_fetch_assoc($sad_q)){
  if (!isset($te_k)){$te_k=array_keys($sad_q_c);}
  if (preg_match('#^'.$sad_prefix.'('.$te_i.')$#i',$sad_q_c[$te_k[0]],$te_a)){
   $te[$te_a[1]]=true;
  }
 }
 unset($te_k,$te_i,$te_a,$sad_q,$sad_q_c);

 if (!$te['data']){
  mysql_query('CREATE TABLE if not exists `'.$sad_prefix.'data` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`i` INT NOT NULL ,
`sname` TEXT NOT NULL ,
`parent` TEXT NOT NULL ,
INDEX (`i`)
) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_unicode_ci COMMENT="'.sad_safe_mysql($sad_domain.' / '.time()).'";');
 }

 if (!$te['_visits']){
  mysql_query('CREATE TABLE IF NOT EXISTS `'.$sad_prefix.'_visits` (
 `id` int(11) NOT NULL auto_increment PRIMARY KEY,
 `requesturi` text NOT NULL,
 `ip` bigint(11) NOT NULL default "0",
 `referer`    text NOT NULL,
 `httphost`   text NOT NULL,
 `useragent`  text NOT NULL,
 `phpsessid`  text NOT NULL,
 `time` int(11) NOT NULL default "0",
 `is_bot` tinyint(4) NOT NULL default "0",
 `iam`    tinyint(4) NOT NULL default "0",
 KEY `time` (`time`),
 KEY `ip` (`ip`)
) ENGINE=MyISAM CHARACTER SET utf8 COLLATE utf8_unicode_ci COMMENT="'.sad_safe_mysql($sad_domain.' / '.time()).'";');
 }

 if (!$te['_users']){
  mysql_query('CREATE TABLE if not exists `'.$sad_prefix.'_users` (
 `id` int(11) NOT NULL auto_increment PRIMARY KEY,
 `login` text NOT NULL,
 `password` text NOT NULL,
 `rights` text NOT NULL
) ENGINE=MyISAM CHARACTER SET utf8 COLLATE utf8_unicode_ci COMMENT="'.sad_safe_mysql($sad_domain.' / '.time()).'";');
  mysql_query('insert into `'.$sad_prefix.'_users` (`login`,`password`,'.
              '`rights`) VALUES ("developer","'.md5('password').'","ad")');
 }

 if (!$te['_history']){
  mysql_query('CREATE TABLE if not exists `'.$sad_prefix.'_history` (
 `id` int(11) NOT NULL auto_increment PRIMARY KEY,
 `title` text NOT NULL,
 `text` text NOT NULL,
 `time` int(11) NOT NULL default "0",
 KEY `time` (`time`)
) ENGINE=MyISAM CHARACTER SET utf8 COLLATE utf8_unicode_ci COMMENT="'.sad_safe_mysql($sad_domain.' / '.time()).'";');
 }
 if (!$te['_options']){
  mysql_query('CREATE TABLE if not exists `'.$sad_prefix.'_options` (
`id` INT NOT NULL PRIMARY KEY
) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_unicode_ci COMMENT="'.sad_safe_mysql($sad_domain.' / '.time()).'";');
  mysql_query('insert into `'.$sad_prefix.'_options` (`id`) VALUES (1)');
 }
 unset($te);

 //Create folders
 $fols=array('templates',
             'templates/static',
             'templates/includes',
             'templates/edit',
             'templates/buttons',
             'images','storage','common','functions');
 foreach ($fols as $fol){
  if (!file_exists($sad_root.'/'.$fol)){mkdir($sad_root.'/'.$fol);}
 }
 unset($fols,$fol);
 if (!file_exists($sad_root.'/htaccess.php')){
  $fo=fopen($sad_root.'/htaccess.php','w');
  if (!$fo){
   fwrite($fo,'<'."?php\r\n //".'$'."sad_url='/';\r\n?".'>');
   fclose($fo);
  }
 }

 //Admin function
 function iam($r='a'){
  return (strpos(' '.$_SESSION['sad_rights'],$r)>0);
 }

 function iamd(){
  return iam('d');
 }

 //Include functions/
 $ff=scandir($sad_root.'/functions');
 foreach ($ff as $f){
  if (filesize($sad_root.'/functions/'.$f)<3){continue;}
  if (!preg_match('_\\.(inc|php)$_i',$f)){continue;}
  if ($f[0]=='#' or $f[0]=='_'){continue;}
  include_once($sad_root.'/functions/'.$f);
 }
 unset($ff,$f);


 //prepare function {#wait:title#}
 function sad_prepare($key,$value){
  global $sad_prepared;
  if (isset($sad_prepared[$key])){
   $sad_prepared[$key]['value']=$value;
  }
 }

 function sad_parse_prepare_in($a){
  global $sad_prepared;
  if (!isset($sad_prepared[$a[2]])){
   $hashes=array(0,1,2,3,4,5,6,7,8,9);$hash='';
   for ($i=ord('a');$i<=ord('z');$i++){
    array_push($hashes,chr($i),strtoupper(chr($i)));
   }
   for ($i=0;$i<16;$i++){
    $hash.=$hashes[mt_rand(0,count($hashes)-1)];
   }
   $sad_prepared[$a[2]]=array('hash'=>$hash);
  }else{$hash=$sad_prepared[$a[2]]['hash'];}
  return '{#wait:'.$hash.':'.$a[2].'#}';
 }

 function sad_parse_prepare($a){
  global $sad_prepared;
  if (!isset($sad_prepared[$a[3]])){return $a[0];}
  if ($sad_prepared[$a[3]]['hash']!==$a[2]){return $a[0];}
  return $sad_prepared[$a[3]]['value'];
 }

 $sad_prepared=array();
 
 //other functions
 function sad_php_version(){
  //PHP_VERSION_ID available since 5.2.7
  preg_match('|^([0-9]+)\.([0-9]+)\.([0-9]+)$|',phpversion(),$a);
  return ((int)$a[1])*10000+((int)$a[2])*100+((int)$a[3]);
 }
 
 function sad_iswin(){
  return (DIRECTORY_SEPARATOR=='\\');
 }
 
 //Debug functions
 if (!isset($_SESSION['error_type'])){$_SESSION['error_type']=error_reporting();}
 if (!isset($_SESSION['error_disp'])){$_SESSION['error_disp']=(int)ini_get('display_errors');}
 
 //parse {#property:blahblah#}
 function sad_property($prop,$mode=''){
  global $sad_name, $sad_parent, $sad_table, $sad_prefix, $sad_temp_id;

  if ($sad_temp_id>0){
   $tmp_sql='`id`='.sad_safe_mysql($sad_temp_id);
  }else{
   $tmp_sql='`sname` like "'.sad_safe_mysql($sad_name).
            '")and(`parent` like "'.sad_safe_mysql($sad_parent).'"';
  }
  $tmp_q=mysql_query('select `'.sad_safe_mysql($prop).'` as '.
            '`value` from `'.sad_safe_mysql($sad_prefix.$sad_table).
            '` where ('.$tmp_sql.') limit 1');
  if (!mysql_error()){
   $tmp_q_c=mysql_fetch_assoc($tmp_q);
   $tmp_value=$tmp_q_c['value'];
   if (strtolower($mode)=='h'){$tmp_value=sad_safe_html($tmp_value);}
   return $tmp_value;
  }

 }

 function sad_parse_property($a){
  return '<'."?php echo sad_property('".$a[2]."','".$a[1]."');?".'>';
 }


 //functions "include"
 function sad_inc_button($button){
  global $sad_table, $sad_name, $sad_parent,
         $sad_prefix,$sad_root, $sad_temp_id, $sad_baseurl, $sad_script;

  if (!iam()){return '';}
  if (file_exists($sad_root.'/templates/buttons/'.$button)){
   ob_start();
   include($sad_root.'/templates/buttons/'.$button);
   $buf=ob_get_contents();
   ob_end_clean();

   if ($sad_temp_id<1){
    $q  =mysql_query('select `id` from `'.$sad_prefix.$sad_table.
             '` where (`parent` like "'.sad_safe_mysql($sad_parent).
             '")and(`sname` like "'.sad_safe_mysql($sad_name).'") limit 1');
    if (!mysql_error()){
     $q_c=mysql_fetch_assoc($q);
     $sad_temp_id=$q_c['id'];
    }
    if (strlen($sad_temp_id)<1){$sad_temp_id='new&amp;sname='.urlencode($sad_name).'&amp;parent='.urlencode($sad_parent);}
   }

   $buf=preg_replace('_\\{#table#\\}_i', $sad_table,  $buf);
   $buf=preg_replace('_\\{#id#\\}_i',    $sad_temp_id,$buf);
   $buf=preg_replace('_\\{#parent#\\}_i',$sad_parent, $buf);
  }else{$buf='';}
  if (iamd()){
   $buf.='<a href="/i/editcode.php?file='.
         urlencode('buttons/'.$button).'" target="_blank" '.
         'title="Edit buttons"><img src="/i/style/puzzle.png" '.
         'alt="edit buttons" style="border: none"></a>';
  }
  $buf=preg_replace('_=("|\')/i_i','=$1'.$sad_baseurl.'/i',$buf);
  return $buf;
 }

 function sad_parse_button($a){
  return '<'.'?php echo sad_inc_button(\''.$a[1].'\'); ?'.'>';
 }

 function sad_parse_sharp_php($a){
  return '<'.'?php echo '.$a[1].';?'.'>';
 }

 //parse option
 function sad_option($a){
  global $sad_options;
  return $sad_options[strtolower($a)];
 }

 function sad_parse_option($a){
  return '<'.'?php echo sad_option("'.$a[1].'");?'.'>';
 }

 function sad_option_refresh(){
  global $sad_prefix, $sad_options;
  $sad_options=array();
  $q_c=mysql_fetch_assoc(mysql_query('select * from `'.$sad_prefix.'_options` where `id`=1'));
  foreach ($q_c as $key => $value){
   if (preg_match('_^(id)$_i',$key)){continue;}
   $sad_options[strtolower($key)]=$value;
  }
 }

 $sad_options=array();
 sad_option_refresh();

 //Parse include
 function sad_parse_include($a){
  global $sad_root;
  $path=$sad_root.'/templates/'.sad_safe_path($a[1]);
  if (file_exists($path)){
   $buf=file_get_contents($path);
   return '?'.'>'.$buf.'<'.'?php ';
  }else{
   return '';
  }
 }

 //Get $sad_name from pair of url & script
 function sad_get_name($sad_url,$sad_b){
  global $sad_name, $sad_parent;
  $t2=preg_replace('|/[^/]+$|','/','/'.$sad_b);
  $t =substr($sad_url,strlen($t2));
  if ($t=='' or $t=='index.php'){$t='main';}
  $sad_name=urldecode($t);$sad_parent=substr($t2,1);
 }

 function sad_parse_file($ismain){
  global $sad_root, $sad_baseurl, $sad_name, $sad_parent, $sad_table, $sad_prefix, 
         $sad_purl, $sad_rurl, $sad_url, $sad_domain, $sad_temp_id, $sad_version,
		 $sad_contype, $sad_url_script, $sad_script, $sad_protocol, $sad_prepared,
		 $sad_hide, $sad_hidetimestamp, $sad_hidewtime, $sad_etag_cache;
  
  //prepare template
  if ($ismain){
   // include
   $sad_tmp=array(file_get_contents($sad_root.'/templates/template.php'),'','');

   $sad_a=explode('/',substr($sad_url_script,1));
   if ($sad_a[count($sad_a)-1]==''){$sad_a[count($sad_a)-1]='index.php';}
   
   if (!preg_match('_/$_',$sad_url_script) and is_dir($sad_root.'/templates/includes/'.$sad_url_script)){
    header('http/1.0 301 goto');
    header('location: '.$sad_baseurl.$sad_url_script.'/');
    exit;
   }
   
   $sad_found_in_include=false;
   $sad_j=count($sad_a);for ($sad_i=0;$sad_i<$sad_j;$sad_i++){
    $sad_b=implode('/',$sad_a);
    if (file_exists($sad_root.'/templates/includes/'.$sad_b) and
        !is_dir($sad_root.'/templates/includes/'.$sad_b)){$sad_found_in_include=true;break;}

    $sad_a[count($sad_a)-1]='default.php';
    $sad_b=implode('/',$sad_a);
    if (file_exists($sad_root.'/templates/includes/'.$sad_b) and
        !is_dir($sad_root.'/templates/includes/'.$sad_b)){$sad_found_in_include=true;break;}

    unset($sad_a[count($sad_a)-1]);
   }
   unset($sad_a,$sad_i,$sad_j);

   $sad_tmp=preg_split('|\\{#!?main#\\}|i',$sad_tmp[0],2);
   $sad_tmp[2]=$sad_tmp[1];
   if ($sad_found_in_include){
    $sad_script='includes/'.$sad_b;
    sad_get_name($sad_url_script,$sad_b);
    $sad_tmp[1]=file_get_contents($sad_root.'/templates/'.$sad_script);
   }else{
    $sad_name=$sad_url;$sad_parent='';
    $sad_tmp[1]='';
   }
   unset($sad_b);
  }else{
   //static
   $sad_tmp=array(file_get_contents($sad_root.'/templates/'.$sad_script),'','');
  }
  
  //tag parsing
  for ($sad_tmp_i=0;$sad_tmp_i<=2;$sad_tmp_i++){
   $sad_tmp[$sad_tmp_i]=preg_replace_callback('|\\{#include:([a-z0-9_./-]+?)#\\}|i','sad_parse_include',$sad_tmp[$sad_tmp_i]);
   $sad_tmp[$sad_tmp_i]=preg_replace_callback('|\\{#php:(.*?)#\\}|i',    'sad_parse_sharp_php',$sad_tmp[$sad_tmp_i]);
   $sad_tmp[$sad_tmp_i]=preg_replace_callback('_\\{#property(|h):(.*?)#\\}_i','sad_parse_property',$sad_tmp[$sad_tmp_i]);
   $sad_tmp[$sad_tmp_i]=preg_replace_callback('_\\{#but:(.*?)#\\}_i',    'sad_parse_button',$sad_tmp[$sad_tmp_i]);
   $sad_tmp[$sad_tmp_i]=preg_replace_callback('_\\{#option:(.*?)#\\}_i', 'sad_parse_option',$sad_tmp[$sad_tmp_i]);
   $sad_tmp[$sad_tmp_i]=preg_replace_callback('/\\{#(wait|prepare|prepared):([a-z0-9._-]+) *#\\}/i','sad_parse_prepare_in',$sad_tmp[$sad_tmp_i]);
  }
  
  //Debug errors
  if (iamd()){
   ini_set('display_errors',$_SESSION['error_disp']);
   $sad_old_ep=error_reporting();
   error_reporting($_SESSION['error_type']);
  }
  
  //compile
  ob_start();
  for ($sad_tmp_i=0;$sad_tmp_i<=2;$sad_tmp_i++){eval('?'.'>'.$sad_tmp[$sad_tmp_i].'<'.'?php ');}
  $body=ob_get_contents();
  ob_end_clean();

  if (iamd()){error_reporting($sad_old_ep);}
  
  //"prepare" parsing
  $body=preg_replace_callback('_\\{#(wait|prepare|prepared):([a-z0-9]{16,16}):(.*?)#\\}_i','sad_parse_prepare',$body);

  return $body;
 }//sad_parse_file

 //End of functions

 if (function_exists('mb_internal_encoding')){mb_internal_encoding('UTF-8');}

 //CONTENT
 if ($sad_inadmin or $sad_inconly){return;}
 $sad_is_bot=0;if (isset($_SERVER['HTTP_X_BOT'])){if ((int)$_SERVER['HTTP_X_BOT']>0){$sad_is_bot=1;}}
 mysql_query('insert into `'.$sad_prefix.'_visits` (`referer`, `useragent`, '.
   '`ip`, `requesturi`,`httphost`, `time`,`is_bot`,`iam`,`phpsessid`) VALUES ("'.
   sad_safe_mysql($_SERVER['HTTP_REFERER']).'", "'.
   sad_safe_mysql($_SERVER['HTTP_USER_AGENT']).'", INET_ATON("'.
   $_SERVER['REMOTE_ADDR'].'"), "'.
   sad_safe_mysql($_SERVER['REQUEST_URI']).'", "'.
   sad_safe_mysql($_SERVER['HTTP_HOST']).'", UNIX_TIMESTAMP(), '.
   $sad_is_bot.', '.(iam() ? 1 : 0).', "'.sad_safe_mysql(session_id()).'")');
 unset($sad_is_bot);

 //variables
 $sad_table ='data';
 $sad_script='';

 //CHANGE URL IF NEED
 $sad_url_orig=$sad_url;
 include($sad_root.'/htaccess.php');
 $sad_url_script=$sad_url;
 $sad_url=$sad_url_orig;unset($sad_url_orig);
 $sad_url_script=preg_replace('_/+_','/',$sad_url_script);
 if ($sad_url_script[0]!=='/'){$sad_url_script='/'.$sad_url_script;}
 //Error reporting
 error_reporting(~E_ALL);

 //search in static
 $sad_a=explode('/',substr($sad_url_script,1));
 if ($sad_a[count($sad_a)-1]==''){$sad_a[count($sad_a)-1]='index.php';}
 
 if (!preg_match('_/$_',$sad_url_script) and is_dir($sad_root.'/templates/static/'.$sad_url_script)){
  header('http/1.0 301 goto');
  header('location: '.$sad_baseurl.$sad_url_script.'/');
  exit;
 }
 
 $sad_found_in_static=false;
 $sad_j=count($sad_a);for ($sad_i=0;$sad_i<$sad_j;$sad_i++){
  $sad_b=implode('/',$sad_a);

  if (file_exists($sad_root.'/templates/static/'.$sad_b) and
      !is_dir($sad_root.'/templates/static/'.$sad_b)){$sad_found_in_static=true;break;}

  $sad_a[count($sad_a)-1]='default.php';
  $sad_b=implode('/',$sad_a);
  if (file_exists($sad_root.'/templates/static/'.$sad_b) and
      !is_dir($sad_root.'/templates/static/'.$sad_b)){$sad_found_in_static=true;break;}

  unset($sad_a[count($sad_a)-1]);
 }
 unset($sad_a,$sad_i,$sad_j);
  
 //set main template
 if ($sad_found_in_static){
  sad_get_name($sad_url_script,$sad_b);
  $sad_script='static/'.$sad_b;
 }
 //PARSE AND RUN TEMPLATE
 $sad_body=sad_parse_file(!$sad_found_in_static);
  
 //prepare html-body
 if (!($sad_hidetimestamp or $sad_hide)){$sad_body.='<!-- '.gmdate('d.m.Y H:i:sO').' -->';}
 if (!($sad_hidewtime or $sad_hide)){list($sad_u2m_sec,$sad_u2s_sec)=explode(' ',microtime()); $sad_body.='<!-- '.($sad_u2s_sec+$sad_u2m_sec-$sad_u1s_sec-$sad_u1m_sec).' -->';}
 
 if (iam() and !$sad_hide){
  $sad_body.='<script src="'.$sad_baseurl.'/i/adminbutton.js"></script>';
 }
 
 //E-tag
 if ($sad_etag_cache){
  if (!isset($sad_etag_hash)){$sad_etag_hash=md5($sad_body);}
  header('ETag: '.$sad_etag_hash);
  header('Cache-control: must-revalidate');
  header('Pragma: ');
  if ($_SERVER['HTTP_IF_NONE_MATCH']==$sad_etag_hash and $sad_etag_hash!==''){
   header('http/1.0 304');
   exit;
  }
 }else{
  header('Cache-control: no-cache');
 }
 
 //ECHO
 if (strlen($sad_contype)>0){header('Content-type: '.$sad_contype);}
 header('Content-length: '.strlen($sad_body));
 echo $sad_body;
?>